package com.aidex.generator.controller;

import com.aidex.common.annotation.Log;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.text.Convert;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.query.QueryGenerator;
import com.aidex.common.utils.StringUtils;
import com.aidex.generator.domain.GenTable;
import com.aidex.generator.domain.GenTableColumn;
import com.aidex.generator.service.GenTableColumnService;
import com.aidex.generator.service.GenTableService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 *
 */
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController<GenTableService> {

    @Autowired
    private GenTableColumnService genTableColumnService;

    /**
     * 查询代码生成列表
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:list')")
    @GetMapping("/list")
    public R page(GenTable genTable,
                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                  HttpServletRequest req) {
        QueryWrapper<GenTable> queryWrapper = QueryGenerator.initQueryWrapper(genTable, req.getParameterMap());
        Page<GenTable> page = new Page<>(pageNo, pageSize);
        IPage<GenTable> pageList = service.selectPage(page, queryWrapper);
        return R.data(pageList);
    }

    /**
     * 修改代码生成业务
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:query')")
    @GetMapping(value = "/{tableId}")
    public R getInfo(@PathVariable String tableId) {
        GenTable table = service.selectById(tableId);
        List<GenTable> tables = service.selectList(new QueryWrapper<>());
        QueryWrapper<GenTableColumn> wrapper = new QueryWrapper<>();
        wrapper.in("table_id", tableId);
        List<GenTableColumn> list = genTableColumnService.selectList(wrapper);
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put("info" , table);
        map.put("rows" , list);
        map.put("tables" , tables);
        return R.data(map);
    }

    /**
     * 查询数据库列表
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:list')")
    @GetMapping("/db/list")
    public R dataList(GenTable genTable) {
        QueryWrapper<GenTable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("table_schema", "(select database())");
        queryWrapper.notLike("table_name", "qrtz_");
        queryWrapper.notLike("table_name", "gen_");
        queryWrapper.notIn("table_name", "(select table_name from gen_table)");
        queryWrapper.like("lower(table_name)", StringUtils.nvl(genTable.getTableName(), ""));
        queryWrapper.like("lower(table_comment)", StringUtils.nvl(genTable.getTableComment(), ""));
        List<GenTable> list = service.selecDbtList(queryWrapper);
        return R.data(list);
    }

    /**
     * 查询数据表字段列表
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:list')")
    @GetMapping(value = "/column/{tableId}")
    public R columnList(String tableId) {
        QueryWrapper<GenTableColumn> wrapper = new QueryWrapper<>();
        wrapper.in("table_id", tableId);
        List<GenTableColumn> list = genTableColumnService.selectList(wrapper);
        return R.data(list);
    }

    /**
     * 导入表结构（保存）
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:import')")
    @Log(title = "代码生成" , businessType = BusinessType.IMPORT)
    @PostMapping("/importTable")
    public R importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        QueryWrapper<GenTable> wrapper = new QueryWrapper<>();
        wrapper.in("table_name", tableNames);
        List<GenTable> tableList = service.selectList(wrapper);
        service.importGenTable(tableList);
        return R.success();
    }

    /**
     * 修改保存代码生成业务(不进行校验)
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:edit')")
    @Log(title = "代码生成" , businessType = BusinessType.UPDATE)
    @PostMapping("/editNoValidated")
    public R editNoValidated(@RequestBody GenTable genTable) {
        service.updateById(genTable);
        return R.success();
    }

    /**
     * 修改保存代码生成业务
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:edit')")
    @Log(title = "代码生成" , businessType = BusinessType.UPDATE)
    @PutMapping
    public R editSave(@Validated @RequestBody GenTable genTable) {
        service.validateEdit(genTable);
        service.updateById(genTable);
        return R.success();
    }

    /**
     * 删除代码生成
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:remove')")
    @Log(title = "代码生成" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{tableIds}")
    public R remove(@PathVariable String[] tableIds) {
        service.deleteBatchIds(Arrays.asList(tableIds));
        return R.success();
    }

    /**
     * 预览代码
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:preview')")
    @GetMapping("/preview/{tableId}")
    public R preview(@PathVariable("tableId") String tableId) throws IOException {
        // 查询表信息
        GenTable genTable = service.selectById(tableId);
        service.validateEdit(genTable);
        Map<String, String> dataMap = service.previewCode(tableId);
        return R.data(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:code')")
    @Log(title = "代码生成" , businessType = BusinessType.GENCODE)
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        String[] tableNames = Convert.toStrArray(tableName);
        // 查询表信息
        QueryWrapper<GenTable> wrapper = new QueryWrapper<>();
        wrapper.in("table_name", tableNames);
        service.validateEdit(service.selectOne(wrapper));
        byte[] data = service.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:code')")
    @Log(title = "代码生成" , businessType = BusinessType.GENCODE)
    @GetMapping("/genCode/{tableName}")
    public R genCode(@PathVariable("tableName") String tableName) {
        String[] tableNames = Convert.toStrArray(tableName);
        // 查询表信息
        QueryWrapper<GenTable> wrapper = new QueryWrapper<>();
        wrapper.in("table_name", tableNames);
        service.validateEdit(service.selectOne(wrapper));
        return R.success(service.generatorCode(tableName));
    }

    /**
     * 同步数据库
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:edit')")
    @Log(title = "代码生成" , businessType = BusinessType.UPDATE)
    @GetMapping("/synchDb/{tableName}")
    public R synchDb(@PathVariable("tableName") String tableName) {
        // service.synchDb(tableName);
        return R.success();
    }

    /**
     * 创建菜单
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:edit')")
    @Log(title = "代码生成" , businessType = BusinessType.UPDATE)
    @GetMapping("/addMenu/{tableName}")
    public R addMenu(@PathVariable("tableName") String tableName) {
        service.addMenu(tableName);
        return R.success();
    }

    /**
     * 批量生成代码
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:code')")
    @Log(title = "代码生成" , businessType = BusinessType.GENCODE)
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = service.downloadCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin" , "*");
        response.addHeader("Access-Control-Expose-Headers" , "Content-Disposition");
        response.setHeader("Content-Disposition" , "attachment; filename=\"ruoyi.zip\"");
        response.addHeader("Content-Length" , "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}